﻿using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using DataModel.KaoShi;
using InterfaceServer;

namespace DLL
{
    public class CURD<T> : ICRUD<T> where T : class
    {
        public void Create(string entitystr)
        {
            var entity = JsonHelp.ParseFormJson<T>(entitystr);
            using (var data = new EFKaoShiContext())
            {
                //var dbentity = data.Entry(entity);
                data.Entry<T>((T) entity);
                data.Set<T>().Add((T) entity);
                data.SaveChanges();
            }
        }

        public void Delete(string entitystr)
        {
            var entity = JsonToEntity.ConvertToEntity<T>(entitystr);
            using (var data = new EFKaoShiContext())
            {
                if (entity != null)
                {
                    //将实体以"UnChanged"的状态放置到上下文中
                    data.Set<T>().Attach(entity as T);
                    //给定实体标记为“已删除”
                    data.Entry(entity).State = EntityState.Deleted;
                    //EFDbContext.Set<TEntity>().Remove(item as TEntity);
                    data.SaveChanges();
                }
            }
        }

        public string get(int id)
        {
            using (var data = new EFKaoShiContext())
            {
                var model= data.Set<T>().Find(id);
                return string.Empty;
            }
        }

        public string getList()
        {
            return string.Empty;
        }

        public void Update(string entitystr)
        {
            var entity = JsonToEntity.ConvertToEntity<T>(entitystr);
            using (var data = new EFKaoShiContext())
            {
                if (entity != null)
                {
                    //将实体以"UnChanged"的状态放置到上下文中
                    data.Set<T>().Attach(entity as T);
                    //更新
                    data.Entry(entity).State = EntityState.Modified;
                    data.SaveChanges();
                }
            }
        }
    }
}
